package com.styletransfer.service;

import com.styletransfer.exception.BusinessException;
import com.styletransfer.mapper.AlbumMapper;
import com.styletransfer.mapper.UserMapper;
import com.styletransfer.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 专辑服务类
 *
 * 这个类负责处理与图片专辑相关的业务逻辑，包括专辑的创建、更新、查询等。
 */
@Service
public class AlbumService {

    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NotificationService notificationService;

    /**
     * 创建专辑
     *
     * @param album 专辑对象
     * @param imageUrls 图片URL列表
     * @return API响应
     */
    @Transactional
    public ApiResponse<Album> createAlbum(Album album, List<String> imageUrls) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        album.setUserId(userId);

        // 检查图片列表
        if (imageUrls == null || imageUrls.isEmpty()) {
            throw new BusinessException("图片列表不能为空");
        }

        // 设置专辑封面图片（使用第一张图片作为封面）
        album.setCoverImage(imageUrls.get(0));

        // 设置图片数量
        album.setImageCount(imageUrls.size());

        // 设置默认值
        album.setLikeCount(0);
        album.setCommentCount(0);
        album.setViewCount(0);
        album.setCreateTime(new Date());
        album.setUpdateTime(new Date());
        album.setStatus(1); // 1:正常, 0:删除

        // 如果没有设置是否公开，默认为公开
        if (album.getIsPublic() == null) {
            album.setIsPublic(1); // 1:公开, 0:私有
        }

        // 插入专辑
        albumMapper.insert(album);

        // 插入专辑图片关联
        for (int i = 0; i < imageUrls.size(); i++) {
            albumMapper.insertAlbumImage(album.getId(), imageUrls.get(i), i);
        }

        // 创建新专辑通知（如果是公开专辑）
        if (album.getIsPublic() == 1) {
            notificationService.createNewAlbumNotification(album.getId(), album.getTitle(), userId);
        }

        return ApiResponse.success(album);
    }

    /**
     * 更新专辑
     *
     * @param album 专辑对象
     * @return API响应
     */
    public ApiResponse<Album> updateAlbum(Album album) {
        // 检查专辑是否存在
        Album existingAlbum = albumMapper.findById(album.getId());
        if (existingAlbum == null) {
            throw new BusinessException("专辑不存在");
        }

        // 检查是否有权限修改
        if (!isAdmin() && !existingAlbum.getUserId().equals(getCurrentUserId())) {
            throw new BusinessException("没有权限修改此专辑");
        }

        // 设置不可修改的字段
        album.setUserId(existingAlbum.getUserId());
        album.setCoverImage(existingAlbum.getCoverImage());
        album.setImageCount(existingAlbum.getImageCount());
        album.setLikeCount(existingAlbum.getLikeCount());
        album.setCommentCount(existingAlbum.getCommentCount());
        album.setViewCount(existingAlbum.getViewCount());
        album.setCreateTime(existingAlbum.getCreateTime());
        album.setStatus(existingAlbum.getStatus());
        album.setUpdateTime(new Date());

        // 更新专辑
        albumMapper.update(album);

        return ApiResponse.success(album);
    }

    /**
     * 删除专辑
     *
     * @param id 专辑ID
     * @return API响应
     */
    @Transactional
    public ApiResponse<Void> deleteAlbum(Long id) {
        // 检查专辑是否存在
        Album album = albumMapper.findById(id);
        if (album == null) {
            throw new BusinessException("专辑不存在");
        }

        // 检查是否有权限删除
        if (!isAdmin() && !album.getUserId().equals(getCurrentUserId())) {
            throw new BusinessException("没有权限删除此专辑");
        }

        // 更新专辑状态为已删除
        albumMapper.updateStatus(id, 0);

        return ApiResponse.success();
    }

    /**
     * 根据ID查询专辑
     *
     * @param id 专辑ID
     * @return API响应
     */
    public ApiResponse<Album> findById(Long id) {
        try {
            Album album = albumMapper.findById(id);
            if (album == null) {
                return ApiResponse.error("专辑不存在");
            }

            // 增加浏览次数
            albumMapper.incrementViewCount(id);

            // 设置用户信息
            if (album.getUserId() != null) {
                album.setUser(userMapper.findById(album.getUserId()));
            }

            // 查询专辑图片
            List<String> images = albumMapper.findAlbumImages(id);
            album.setImages(images);

            // 查询当前用户是否点赞
            if (SecurityContextHolder.getContext().getAuthentication() != null) {
                Long userId = getCurrentUserId();
                if (userId != null) {
                    album.setIsLiked(albumMapper.isLiked(userId, id) > 0);
                }
            }

            return ApiResponse.success(album);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询用户的专辑
     *
     * @param userId 用户ID
     * @return API响应
     */
    public ApiResponse<List<Album>> findByUser(Long userId) {
        try {
            List<Album> albums = albumMapper.findByUser(userId);

            // 设置用户信息和专辑图片
            for (Album album : albums) {
                if (album.getUserId() != null) {
                    album.setUser(userMapper.findById(album.getUserId()));
                }

                // 查询专辑图片
                List<String> images = albumMapper.findAlbumImages(album.getId());
                album.setImages(images);
            }

            return ApiResponse.success(albums);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询用户的专辑
     *
     * @param userId 用户ID
     * @param pageRequest 分页请求
     * @return API响应
     */
    public ApiResponse<PageResponse<Album>> findByUserPage(Long userId, PageRequest pageRequest) {
        try {
            userId = this.getCurrentUserId();
            // 计算偏移量
            Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

            // 查询专辑列表
            List<Album> albums = albumMapper.findByUserPage(userId, offset, pageRequest.getPageSize());

            // 设置用户信息和专辑图片
            for (Album album : albums) {
                if (album.getUserId() != null) {
                    album.setUser(userMapper.findById(album.getUserId()));
                }

                // 查询专辑图片
                List<String> images = albumMapper.findAlbumImages(album.getId());
                album.setImages(images);
            }

            // 查询总数
            Long total = albumMapper.countByUser(userId);

            // 构建分页响应
            PageResponse<Album> pageResponse = new PageResponse<>(albums, total, pageRequest.getPageNum(), pageRequest.getPageSize());

            return ApiResponse.success(pageResponse);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询公开的专辑
     *
     * @return API响应
     */
    public ApiResponse<List<Album>> findPublic() {
        try {
            List<Album> albums = albumMapper.findPublic();

            // 设置用户信息和专辑图片
            for (Album album : albums) {
                if (album.getUserId() != null) {
                    album.setUser(userMapper.findById(album.getUserId()));
                }

                // 查询专辑图片
                List<String> images = albumMapper.findAlbumImages(album.getId());
                album.setImages(images);
            }

            return ApiResponse.success(albums);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询公开的专辑
     *
     * @param pageRequest 分页请求
     * @return API响应
     */
    public ApiResponse<PageResponse<Album>> findPublicPage(PageRequest pageRequest) {
        try {
            // 计算偏移量
            Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

            // 查询专辑列表
            List<Album> albums = albumMapper.findPublicPage(offset, pageRequest.getPageSize());

            // 设置用户信息和专辑图片
            for (Album album : albums) {
                if (album.getUserId() != null) {
                    album.setUser(userMapper.findById(album.getUserId()));
                }

                // 查询专辑图片
                List<String> images = albumMapper.findAlbumImages(album.getId());
                album.setImages(images);
            }

            // 查询总数
            Long total = albumMapper.countPublic();

            // 构建分页响应
            PageResponse<Album> pageResponse = new PageResponse<>(albums, total, pageRequest.getPageNum(), pageRequest.getPageSize());

            return ApiResponse.success(pageResponse);
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户ID
     *
     * @return 用户ID
     */
    private Long getCurrentUserId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object principal = authentication.getPrincipal();

            // 从自定义UserDetails中获取用户ID
            if (principal instanceof com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) {
                return ((com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) principal).getUserId();
            }

            // 尝试从请求属性中获取用户ID
            javax.servlet.http.HttpServletRequest request =
                    ((org.springframework.web.context.request.ServletRequestAttributes)
                            org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).getRequest();
            Object userId = request.getAttribute("userId");
            if (userId != null) {
                return (Long) userId;
            }

            throw new RuntimeException("无法获取用户ID");
        } catch (Exception e) {
            throw new RuntimeException("获取用户ID失败: " + e.getMessage());
        }
    }

    /**
     * 检查当前用户是否为管理员
     *
     * @return 是否为管理员
     */
    private boolean isAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
    }
}
